import {Injectable} from '@angular/core';

@Injectable({
    providedIn: 'root',
})
export class StorageService {
    storage: Storage;

    // private storage: any;
    constructor() {
        this.storage = localStorage;
    }
    async write(key: string, value: any) {
        return await this.storage.set(key, value);
    }
    async read(key: string): Promise<any> {
        let info = JSON.parse(JSON.stringify(await this.storage.get(key)));
        if (typeof info === 'string') {
            try {
                info = JSON.parse(info);
            } catch (e) {
            }
        }
        return info;
    }
    add(key: string, value: any, expireIn?: number) {
        let value1: StorageValue = JSON.parse(this.storage.getItem(key));
        if (expireIn) {
            value1 = {key, value, expireTime: new Date(new Date().getTime() + expireIn)};
        } else {
            value1 = {key, value};
        }
        return this.storage.setItem(key, JSON.stringify(value1));
    }

    get(key: string) {
        const val: StorageValue = JSON.parse(this.storage.getItem(key));
        if (val && val.expireTime) {
            return val.expireTime > new Date() ? val.value : undefined;
            // this.storage.remove(key);
        }
        return val ? val.value : undefined;
    }

    set(key: string, value: any, expireIn?: number) {
        let value1: StorageValue;
        if (expireIn) {
            value1 = {key, value, expireTime: new Date(new Date().getTime() + expireIn)};
        } else {
            value1 = {key, value};
        }
        return this.storage.setItem(key, JSON.stringify(value1));
    }

    clear() {
        return this.storage.clear();
    }

    remove(key: string) {
        return this.storage.remove(key);
    }
}


export interface StorageValue {
    key: string;
    value: any;
    expireTime?: Date;
}
